package com.jdwx.opengl.test;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author bai
 * @date 2020/6/30
 * @description
 */
class FairLock {

    public static void main(String[] args) {
        PrintQueue printQueue = new PrintQueue();
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(new Job(printQueue));
        }

        for (int i=0;i<10;i++){
            threads[i].start();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    static class Job implements Runnable{
        private PrintQueue printQueue;

        public Job(PrintQueue printQueue) {
            this.printQueue = printQueue;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"开始打印");
            printQueue.printDocument(new Object());
            System.out.println(Thread.currentThread().getName()+"打印结束");
        }
    }
    static class PrintQueue {
        //公平锁
        private Lock queueLock = new ReentrantLock(true);

        public void printDocument(Object document) {
            queueLock.lock();
            try {
                int duration =new Random().nextInt(10)+1;
                System.out.println(Thread.currentThread().getName() + "正在执行文件打印操作,需要"+duration);
                Thread.sleep(duration*1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                queueLock.unlock();
            }
            //打印两份
            queueLock.lock();
            try {
                int duration =new Random().nextInt(10)+1;
                System.out.println(Thread.currentThread().getName() + "正在执行文件打印操作,需要"+duration);
                Thread.sleep(duration*1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                queueLock.unlock();
            }
        }
    }
}
